package au.com.iglootech.winerymap.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import au.com.iglootech.winerymap.entity.WMUser;
import au.com.iglootech.winerymap.service.WMUserService;
import au.com.iglootech.winerymap.service.dao.GenericDao;

import com.google.appengine.api.datastore.Key;

/**
 * 
 * @author zhuhome
 * 
 */
@Component(WMUserServiceImpl.BEAN_NAME)
public class WMUserServiceImpl implements WMUserService {

	public static final String BEAN_NAME = "WMUserServiceImpl";
	private static final Logger LOG = Logger.getLogger(WMUserServiceImpl.class);

	@Autowired
	private transient GenericDao genericDao;

	@Override
	public WMUser createUser(final WMUser user) {
		return genericDao.save(user);
	}

	@Override
	public WMUser findUser(final String username, final String password) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("pUsername", username);
		params.put("pPassword", password);
		List<WMUser> result = new ArrayList<WMUser>(genericDao.findByNamedQuery(WMUser.class, WMUser.FIND_BY_USERNAME, params));
		if (result == null || result.size() <= 0) {
			return null;
		} else {
			if (result.size() > 1) {
				LOG.error("The user name " + username + " are duplicated, please contact system administrator.");
				return null;
			}
			return genericDao.getJdoTemplate().detachCopy(result.get(0));
		}
	}

	@Override
	public WMUser findByKey(final Key key) {
		return genericDao.findByKey(WMUser.class, key);
	}

}
